<template>
    <div class="list-common-table">
        <!--   搜索部分   -->
        <t-form v-if="searchParams && searchParams.length" ref="form" :data="formData" :label-width="80" colon @reset="onReset" @submit="onSearch">
            <t-row>
                <t-col :span="10">
                    <t-row :gutter="[24, 24]">
                        <t-col :span="4" v-for="(item, index) in searchParams" :key="index">
                            <t-form-item :label="item.label" :name="item.key" v-if="!item.hide">
                                <t-input v-if="item.valueType != 'select'" v-model="formData[`${item.key}`]" clearable />
                                <t-select v-else v-model="formData[`${item.key}`]" :options="item.options" clearable />
                            </t-form-item>
                        </t-col>
                    </t-row>
                </t-col>
                <t-col :span="2" class="operation-container">
                    <t-button theme="primary" type="submit" :style="{ marginLeft: 'var(--td-comp-margin-s)' }">
                        {{ $t('components.commonTable.query') }}
                    </t-button>
                    <t-button type="reset" variant="base" theme="default">
                        {{ $t('components.commonTable.reset') }}
                    </t-button>
                </t-col>
            </t-row>
        </t-form>
        <div style="padding: 10px 10px">
            <slot name="tableHeader"></slot>
        </div>
        <div class="table-container">
            <t-enhanced-table
                v-if="tree"
                :data="data"
                :columns="columns"
                :key="true"
                :selected-row-keys="selectedRowKeys"
                @select-change="onSelectedRowKeys"
                :pagination="pagination"
                :loading="loading"
                :tree="treeConfig"/>
            <t-table
                v-else
                :data="data"
                :columns="columns"
                :row-key="rowKey"
                :max-height="500"
                :selected-row-keys="selectedRowKeys"
                @select-change="onSelectedRowKeys"
                :pagination="pagination"
                :loading="loading"
                @page-change="pageChange"
            />
        </div>
    </div>
</template>


<script setup lang="ts">

import {onMounted, PropType, ref} from "vue";
import {FormInstanceFunctions, PageInfo, PaginationProps, TableTreeConfig} from "tdesign-vue-next";

const form = ref<FormInstanceFunctions>(null);
const formData = ref({});
const data = ref([]);
const selectedRowKeys = ref([]);
const loading = ref(false);
const props = defineProps({
    searchParams: {
        type: Array as PropType<SearchParamsProps[]>
    },
    columns: {
        type: Array
    },
    rowKey: {
        type: String,
        default: 'id'
    },
    pageSizes: {
        type: Array,
        default: [10, 20, 50, 100]
    },
    asyncFc: {
        type: Function
    },
    page: {
        type: Boolean,
        default: true
    },
    /** 是否为树形结构表格 */
    tree: {
        type: Boolean,
        default: false
    },
    treeConfig: {
        type: Object as PropType<TableTreeConfig>,
        default: { childrenKey: 'children' }
    }
});
/**
 * 组件初始进来，判断是否存在表单项默认值
 */
if (props.searchParams && props.searchParams.length) {
    const data = {};
    // 迭代表单项
    props.searchParams.forEach(item => {
        // 如果存在默认值 null undefined 0 '0'
        if (item.defaultValue || item.defaultValue == 0) {
            // 将表单项value-v-model赋值
            data[item.key] = item.defaultValue;
        }
    });
    formData.value = data;
}

const pagination = ref<PaginationProps>(props.page ? {
    defaultCurrent: 1,
    defaultPageSize: 10,
    total: 0,
    pageSizeOptions: props.pageSizes
} : null);

const findData = async (pageNo, pageSize, params) => {
    loading.value = true;
    try {
        const response = await props.asyncFc(props.page ? {pageNo, pageSize, params} : params);
        if (props.page) {
            data.value = response.records;
            if (response.total == 0) {
                pagination.value = false;
            } else {
                pagination.value = {
                    defaultCurrent: 1,
                    defaultPageSize: 10,
                    pageSizeOptions: props.pageSizes,
                    ...pagination.value,
                    total: response.total,
                };
            }

        } else {
            data.value = response;
        }
    } catch (e) {
        console.log(e);
    } finally {
        loading.value = false;
    }
}

const onReset = () => {
    // 重置表单
    form.value.reset();
    findData(pagination.value?.defaultCurrent, pagination.value?.defaultPageSize, {});
}

const onSearch = (params?: any) => {
    findData(pagination.value?.defaultCurrent, pagination.value?.defaultPageSize, { ...formData.value, ...params });
}

const pageChange = ({current, pageSize}: PageInfo) => {
    findData(current, pageSize, formData.value);
}

const onSelectedRowKeys = (value) => {
    selectedRowKeys.value = value;
}

onMounted(() => {
    findData(pagination.value?.defaultCurrent, pagination.value?.defaultPageSize, formData.value);
});

/**
 * 子组件暴露给父组件调用的方法
 */
defineExpose({ onSearch, getSelectedKeys: () => selectedRowKeys.value });
</script>
<style lang="less" scoped>
.list-common-table {
    background-color: var(--td-bg-color-container);
    padding:  5px 5px;
    border-radius: var(--td-radius-medium);

    .table-container {
        margin-top: var(--td-comp-margin-xxl);
    }
}

.form-item-content {
    width: 100%;
}

.operation-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .expand {
        .t-button__text {
            display: flex;
            align-items: center;
        }
    }
}

.payment-col {
    display: flex;

    .trend-container {
        display: flex;
        align-items: center;
        margin-left: var(--td-comp-margin-s);
    }
}
</style>
